package indi.zjh.dp.util;


import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.print.attribute.standard.Finishings;

import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.error.ConfigureInvalidException;
import indi.zjh.dp.startup.Constant;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisUtil {
    //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
    private static boolean TEST_ON_BORROW = true;
    
    private static JedisPool jedisPool = null;
    
    private static boolean isCluster = false;
    
    private static JedisPoolConfig config;
    private static Set<HostAndPort> clusternodes;
    private static JedisCluster instance = null;
    private static boolean isEnable = true;
    /**
     * 初始化Redis连接池
     */
    public static void init()
    {
        try {
    		isEnable = Configuration.getInstance().getRedisConf().enable;
    		if(isEnable == false)
    			return;
    		
    		String nodes = Configuration.getInstance().getRedisConf().host;
    		String[] host = nodes.split(",");
    		
        	int max_connection = Configuration.getInstance().getRedisConf().maxConnection;
        	String auth = Configuration.getInstance().getRedisConf().auth;
        	int max_idle_connection = Configuration.getInstance().getRedisConf().maxIdleConnection;
        	int connection_wait_timeout = Configuration.getInstance().getRedisConf().connectionWaitTimeout;
        	int connection_timeout = Configuration.getInstance().getRedisConf().connectionTimeout;
        	
            config = new JedisPoolConfig();
            config.setMaxTotal(max_connection);
            config.setMaxIdle(max_idle_connection);
            config.setMaxWaitMillis(connection_wait_timeout);
            config.setTestOnBorrow(TEST_ON_BORROW);
            
            if(host.length == 0)
            {
            	throw new ConfigureInvalidException("没有配置redis/host");
            }
            
            if(host.length  == 1)
            {
            	isCluster = false;
            	String[] parts = host[0].split(":");
        		String node_ip = parts[0].trim();
        		int node_port = Integer.parseInt(parts[1]);
        		
	            if(auth.length() > 0)
	            	jedisPool = new JedisPool(config, node_ip, node_port, connection_timeout, auth);
	            else
	            	jedisPool = new JedisPool(config, node_ip, node_port, connection_timeout);
            }
            else
            {
            	isCluster = true;
            	clusternodes = new LinkedHashSet<HostAndPort>();
            	for(int i = 0; i < host.length; ++i)
            	{
            		String[] parts = host[i].split(":");
            		String node_ip = parts[0].trim();
            		int node_port = Integer.parseInt(parts[1]);
            		clusternodes.add(new HostAndPort(node_ip, node_port));
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static boolean isCluster()
    {
    	return isCluster;
    }
    
    /**
     * 确定缓存是否打开
     * @return
     */
    public static boolean isEnable()
    {
    	return isEnable;
    }
    
    public static void disable()
    {
    	isEnable = false;
    }
    
    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
    	if(isCluster)
    		return null;
        try {
            if (jedisPool != null) {
                Jedis jedis = jedisPool.getResource();
                return jedis;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    
    
    public synchronized static JedisCluster getJedisCluster()
    {
    	if(!isCluster)
    	{
    		return null;
    	}
    	
    	if(instance == null)
    	{
    		instance = new JedisCluster(clusternodes, config);
    	}
    	return instance;
    	
    }
    
    public static void finish() throws IOException
    {
    	if(isCluster)
    	{
    		if(instance != null)
    			instance.close();
    	}
    	else
    	{
    		if(jedisPool != null)
    			jedisPool.close();
    	}
    }

    
    
    
}
